package com.blue.base.oauth.gateway.config.filters;

import lombok.extern.slf4j.Slf4j;
import org.reactivestreams.Publisher;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.function.Function;

/**
 * @author liulei
 * @version 1.0
 */
@Slf4j
public abstract class AbstractWebFilter implements GlobalFilter, Ordered {

    /**
     * 获取执行结果，及后续的操作
     */
    public ServerHttpResponseDecorator getResponseData(ServerWebExchange exchange, Function<String, String> function) {
        ServerHttpResponse serverHttpResponse = exchange.getResponse();
        DataBufferFactory bufferFactory = serverHttpResponse.bufferFactory();
        ServerHttpResponseDecorator decoratedResponse = new ServerHttpResponseDecorator(serverHttpResponse) {
            @Override
            public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
                if (body instanceof Flux) {
                    Flux<? extends DataBuffer> fluxBody = (Flux<? extends DataBuffer>) body;
                    return super.writeWith(fluxBody.map(dataBuffer -> {
                        byte[] content = new byte[dataBuffer.readableByteCount()];
                        dataBuffer.read(content);
                        DataBufferUtils.release(dataBuffer);
                        // 回调函数核心
                        String finalResponse = function.apply(new String(content, StandardCharsets.UTF_8));
                        byte[] uppedContent = new String(finalResponse.getBytes(), StandardCharsets.UTF_8).getBytes();
                        return bufferFactory.wrap(uppedContent);
                    }));
                }
                return super.writeWith(body);
            }
        };
        return decoratedResponse;
    }

    /**
     * 获取参数
     */
    public String getParameter(ServerWebExchange exchange, String parameter) {
        return String.valueOf(exchange.getRequest().getQueryParams().get(parameter));
    }

    /**
     * 获取request的url
     */
    public String getServletPath(ServerWebExchange exchange) {
        ServerHttpRequest serverHttpRequest = exchange.getRequest();
        return serverHttpRequest.getURI().getPath();
    }
}
